package com.blikoon.qrcodescannerlibrary.slice;

import com.blikoon.qrcodescanner.decode.QrManager;
import com.blikoon.qrcodescannerlibrary.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.Button;
import ohos.agp.components.DirectionalLayout;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.Text;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.dialog.BaseDialog;
import ohos.agp.window.dialog.CommonDialog;
import ohos.agp.window.service.DisplayAttributes;
import ohos.agp.window.service.DisplayManager;
import ohos.app.Context;

public class MainAbilitySlice extends AbilitySlice {

    private Button button;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        button = (Button) findComponentById(ResourceTable.Id_button);

        button.setClickedListener(v -> {
            QrManager.getInstance().startScan(this, new QrManager.OnScanResultCallback() {

                @Override
                public void onScanSuccess(String result) {
                    getUITaskDispatcher().asyncDispatch(new Runnable() {
                        @Override
                        public void run() {
                            show(getContext(),result);
                        }
                    });
                }
            });
        });
    }

    private void show(Context context, String text) {
        DirectionalLayout directionalLayout = (DirectionalLayout) LayoutScatter.getInstance(context)
                .parse(ResourceTable.Layout_dialog_picker, null, false);
        Text result = (Text) directionalLayout.findComponentById(ResourceTable.Id_tv_result);
        Text confirm = (Text) directionalLayout.findComponentById(ResourceTable.Id_tv_confirm);
        CommonDialog dialog = new CommonDialog(context);
        dialog.setContentCustomComponent(directionalLayout);
        dialog.setAutoClosable(true);
        dialog.setAutoClosable(true);
        dialog.setSize(vp2px(this,340),DirectionalLayout.LayoutConfig.MATCH_CONTENT);
        dialog.setAlignment(LayoutAlignment.CENTER);
        dialog.setCornerRadius(vp2px(this,15));
        dialog.show();
        result.setText(text);
        confirm.setClickedListener(v -> {
            dialog.destroy();
        });
    }

    /**
     * vp转像素
     *
     * @param context
     * @param vp
     * @return int
     */
    private int vp2px(Context context, float vp) {
        DisplayAttributes attributes = DisplayManager.getInstance().getDefaultDisplay(context).get().getAttributes();
        return (int) (attributes.densityPixels * vp);
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
}
